﻿package nl.justobjects.pushlet.test;

import java.util.HashMap;
import java.util.Map;

import nl.justobjects.pushlet.client.PushletClient;
import nl.justobjects.pushlet.client.PushletClientListener;
import nl.justobjects.pushlet.core.Dispatcher;
import nl.justobjects.pushlet.core.Event;
import nl.justobjects.pushlet.core.Protocol;
import nl.justobjects.pushlet.util.PushletException;

import org.apache.commons.lang.StringUtils;

import CommProxy.CBasicParameter;
import CommProxy.InstructionFrame;

import com.wasion.gydpe.common.util.ConvertInXBaseUtil;
import com.wasion.gydpe.ice.TestProperties;

public class PushletPingApplication extends Thread implements
		PushletClientListener, Protocol {
	int seqNr = 1;
	private PushletClient pushletClient;
	private String host;
	private int port;
	private String id;
	public CBasicParameter frame = null;
	private String SUBJECT = "";
	private static final long PUBLISH_INTERVAL_MILLIS = 5000;
	private static volatile HashMap devaddr_eleMap = new HashMap();

	public PushletPingApplication(String aHost, int aPort,
			CBasicParameter aFrame) {
		host = aHost;
		port = aPort;
		frame = aFrame;
	}

	public PushletPingApplication() {

	}

	public PushletPingApplication(String aHost, int aPort, String Id) {
		host = aHost;
		port = aPort;
		id = Id;
	}

	public synchronized void syn_pushletclient(Map eventData, int seqNr)
			throws PushletException {
		// try {
		pushletClient.publish(SUBJECT, eventData);
		p("published ping # " + (seqNr - 1) + " - sleeping...");

		// Thread.sleep(PUBLISH_INTERVAL_MILLIS);
		/*
		 * } catch (InterruptedException e) { // TODO Auto-generated catch block
		 * //log.loger.error(e.getMessage()); e.printStackTrace(); }
		 */
	}

	public static String byte2String(byte byteVal) {
		String hex = Integer.toHexString(byteVal & 0xFF);
		if (hex.length() == 1) {
			hex = "0" + hex;
		}
		return hex;
	}

	public void run() {

		try {
			/**
			 * 这里要执行数据库插入操作，操作主要是断开故障指示器和断开终端插入，连接故障指示器和连接终端操作，这里分为几个函数进行处理
			 */
			if (frame != null && !StringUtils.isNotEmpty(id)) {
				InstructionFrame frame2 = (InstructionFrame) frame;
				Map eventData = null;
				byte[] data = frame2.frame.data;
				// String result = getHexString(data);
				if (data.length > 11) {
					if (data[0] == 0x01
							&& data[1] == 0x01
							&& data[3] == 0x0b
							&& (data[2] == 0x01 || data[2] == 0x02 || data[2] == 0x04)) {// A、B、C三相电压曲线

						eventData = new HashMap();
						// 获取起始时间
						StringBuffer sb = new StringBuffer();
						String startTime = sb.append("20").append(
								byte2String(data[8])).append("-").append(
								byte2String(data[7])).append("-").append(
								byte2String(data[6])).append(" ").append(
								byte2String(data[5])).append(":").append(
								byte2String(data[4])).toString()
								+ ":00";

						// 将电压值以：拼接串，如87 21为连续的响应值，表示电压值217.8V
						StringBuffer volBuffer = new StringBuffer();
						String lastVal = "";
						for (int i = 0 + 11; i < data.length; i += 2) {
							if (!"ee"
									.equalsIgnoreCase(byte2String(data[i + 1]))) {
								String high = byte2String(data[i + 1]);
								String low = byte2String(data[i]);
								String valOfVol = high + low.substring(0, 1)
										+ "." + low.substring(1);
								lastVal = valOfVol;
								volBuffer.append(valOfVol);
							} else {
								volBuffer.append(lastVal);
							}
							if (data.length - 2 > i) {
								volBuffer.append(":");
							}
						}

						eventData.put("pnfn", "0101" + byte2String(data[2])
								+ "0b");
						eventData.put("startTime", startTime);
						eventData.put("volData", volBuffer.toString());
						Event event = Event.createDataEvent("/source/voltage",
								eventData);
						Dispatcher d = Dispatcher.getInstance();
						d.multicast(event);

					} else if (data[0] == 0x01
							&& data[1] == 0x01
							&& data[3] == 0x0b
							&& (data[2] == 0x08 || data[2] == 0x10 || data[2] == 0x20)) {// A、B、C三相电流曲线

						eventData = new HashMap();
						// 获取起始时间
						StringBuffer sb = new StringBuffer();
						String startTime = sb.append("20").append(
								byte2String(data[8])).append("-").append(
								byte2String(data[7])).append("-").append(
								byte2String(data[6])).append(" ").append(
								byte2String(data[5])).append(":").append(
								byte2String(data[4])).toString()
								+ ":00";

						// 将电流值以:拼接串
						StringBuffer currentBuffer = new StringBuffer();
						String lastVal = "";
						for (int i = 0 + 11; i < data.length; i += 3) {

							if (!"ee"
									.equalsIgnoreCase(byte2String(data[i + 2]))) {
								String highBin = ConvertInXBaseUtil
										.decimal2Binary(ConvertInXBaseUtil
												.byte2Decimal(data[i + 2]),
												true);
								String s = highBin.substring(0, 1);
								String high = ConvertInXBaseUtil.binary2Hex("0"
										+ highBin.substring(1));
								// String high = byte2String(data[i + 2]);
								String middle = byte2String(data[i + 1]);
								String low = byte2String(data[i]);

								// 如果第一位是1，则表示负数；0表示是正数
								String symbol = "";
								if ("1".equals(s)) {
									symbol = "-";
								}
								String valOfCurrent = symbol + high
										+ middle.substring(0, 1) + "."
										+ middle.substring(1) + low;
								lastVal = valOfCurrent;
								currentBuffer.append(valOfCurrent);
							} else {
								currentBuffer.append(lastVal);
							}

							if (data.length - 3 > i) {
								currentBuffer.append(":");
							}
						}

						eventData.put("pnfn", "0101" + byte2String(data[2])
								+ "0b");
						eventData.put("startTime", startTime);
						eventData.put("currentData", currentBuffer.toString());
						Event event = Event.createDataEvent("/source/current",
								eventData);
						Dispatcher d = Dispatcher.getInstance();
						d.multicast(event);

					} else if (data[0] == 0x01
							&& data[1] == 0x01
							&& data[3] == 0x0a
							&& (data[2] == 0x01 || data[2] == 0x02
									|| data[2] == 0x04 || data[2] == 0x08)) {// 有功功率、A、B、C三相有功功率曲线

						eventData = new HashMap();
						// 获取起始时间
						StringBuffer sb = new StringBuffer();
						String startTime = sb.append("20").append(
								byte2String(data[8])).append("-").append(
								byte2String(data[7])).append("-").append(
								byte2String(data[6])).append(" ").append(
								byte2String(data[5])).append(":").append(
								byte2String(data[4])).toString()
								+ ":00";

						// 将有功功率值以:拼接串
						StringBuffer activePowerBuffer = new StringBuffer();
						String lastVal = "";
						for (int i = 0 + 11; i < data.length; i += 3) {

							if (!"ee"
									.equalsIgnoreCase(byte2String(data[i + 2]))) {
								String highBin = ConvertInXBaseUtil
										.decimal2Binary(ConvertInXBaseUtil
												.byte2Decimal(data[i + 2]),
												true);
								String s = highBin.substring(0, 1);
								String high = ConvertInXBaseUtil.binary2Hex("0"
										+ highBin.substring(1));
								// String high = byte2String(data[i + 2]);
								String middle = byte2String(data[i + 1]);
								String low = byte2String(data[i]);

								// 如果第一位是1，则表示负数；0表示是正数
								String symbol = "";
								if ("1".equals(s)) {
									symbol = "-";
								}
								String valOfActivePower = symbol + high + "."
										+ middle + low;
								lastVal = valOfActivePower;
								activePowerBuffer.append(valOfActivePower);
							} else {
								activePowerBuffer.append(lastVal);
							}

							if (data.length - 3 > i) {
								activePowerBuffer.append(":");
							}
						}

						eventData.put("pnfn", "0101" + byte2String(data[2])
								+ "0a");
						eventData.put("startTime", startTime);
						eventData.put("activePowerData", activePowerBuffer
								.toString());
						Event event = Event.createDataEvent(
								"/source/activePower", eventData);
						Dispatcher d = Dispatcher.getInstance();
						d.multicast(event);

					}/*******************************************************
						 * else if (data[0] == 0x01 && data[1] == 0x01 &&
						 * data[3] == 0x0a && (data[2] == 0x10 || data[2] ==
						 * 0x20 || data[2] == 0x40 || Integer2Hex
						 * .byte2Int(data[2]) == 0x80)) {// 无功功率、A、B、C三相无功功率曲线
						 * 
						 * eventData = new HashMap(); // 获取起始时间 StringBuffer sb =
						 * new StringBuffer(); String startTime =
						 * sb.append("20").append(
						 * byte2String(data[8])).append("-").append(
						 * byte2String(data[7])).append("-").append(
						 * byte2String(data[6])).append(" ").append(
						 * byte2String(data[5])).append(":").append(
						 * byte2String(data[4])).toString() + ":00"; //
						 * 将無功功率值以:拼接串 StringBuffer reactivePowerBuffer = new
						 * StringBuffer(); String lastVal = ""; for (int i = 0 +
						 * 11; i < data.length; i += 3) {
						 * 
						 * if (!"ee" .equalsIgnoreCase(byte2String(data[i +
						 * 2]))) { String highBin = ConvertInXBaseUtil
						 * .decimal2Binary(ConvertInXBaseUtil
						 * .byte2Decimal(data[i + 2]), true); String s =
						 * highBin.substring(0, 1); String high =
						 * ConvertInXBaseUtil.binary2Hex("0" +
						 * highBin.substring(1)); // String high =
						 * byte2String(data[i + 2]); String middle =
						 * byte2String(data[i + 1]); String low =
						 * byte2String(data[i]); // 如果第一位是1，则表示负数；0表示是正数 String
						 * symbol = ""; if ("1".equals(s)) { symbol = "-"; }
						 * String valOfReactivePower = symbol + high + "." +
						 * middle + low; lastVal = valOfReactivePower;
						 * reactivePowerBuffer.append(valOfReactivePower); }
						 * else { reactivePowerBuffer.append(lastVal); }
						 * 
						 * if (data.length - 3 > i) {
						 * reactivePowerBuffer.append(":"); } }
						 * 
						 * eventData.put("pnfn", "0101" + byte2String(data[2]) +
						 * "0a"); eventData.put("startTime", startTime);
						 * eventData.put("reactivePowerData",
						 * reactivePowerBuffer .toString()); Event event =
						 * Event.createDataEvent( "/source/reactivePower",
						 * eventData); Dispatcher d = Dispatcher.getInstance();
						 * d.multicast(event); }
						 ******************************************************/
					else if (data[0] == 0x01
							&& data[1] == 0x01
							&& data[3] == 0x0d
							&& (data[2] == 0x01 || data[2] == 0x02
									|| data[2] == 0x04 || data[2] == 0x08)) {// 功率因素、A、B、C三相功率因数曲线

						eventData = new HashMap();
						// 获取起始时间
						StringBuffer sb = new StringBuffer();
						String startTime = sb.append("20").append(
								byte2String(data[8])).append("-").append(
								byte2String(data[7])).append("-").append(
								byte2String(data[6])).append(" ").append(
								byte2String(data[5])).append(":").append(
								byte2String(data[4])).toString()
								+ ":00";

						// 将功率因数值以:拼接串
						StringBuffer powerFactorBuffer = new StringBuffer();
						String lastVal = "";
						for (int i = 0 + 11; i < data.length; i += 2) {
							if (!"ee"
									.equalsIgnoreCase(byte2String(data[i + 1]))) {
								String highBin = ConvertInXBaseUtil
										.decimal2Binary(ConvertInXBaseUtil
												.byte2Decimal(data[i + 1]),
												true);
								String s = highBin.substring(0, 1);
								String high = ConvertInXBaseUtil.binary2Hex("0"
										+ highBin.substring(1));
								// String high = byte2String(data[i + 1]);
								String low = byte2String(data[i]);

								// 如果第一位是1，则表示负数；0表示是正数
								String symbol = "";
								if ("1".equals(s)) {
									symbol = "-";
								}
								String valOfPowerFactor = symbol + high
										+ low.substring(0, 1) + "."
										+ low.substring(1);
								lastVal = valOfPowerFactor;
								powerFactorBuffer.append(valOfPowerFactor);
							} else {
								powerFactorBuffer.append(lastVal);
							}

							if (data.length - 2 > i) {
								powerFactorBuffer.append(":");
							}
						}

						eventData.put("pnfn", "0101" + byte2String(data[2])
								+ "0d");
						eventData.put("startTime", startTime);
						eventData.put("powerFactorData", powerFactorBuffer
								.toString());
						Event event = Event.createDataEvent(
								"/source/powerFactor", eventData);
						Dispatcher d = Dispatcher.getInstance();
						d.multicast(event);

					} else if (data[0] == 0x01 && data[1] == 0x01
							&& data[3] == 0x0b && data[2] == 0x40) {// 零序电流曲线

						eventData = new HashMap();
						// 获取起始时间
						StringBuffer sb = new StringBuffer();
						String startTime = sb.append("20").append(
								byte2String(data[8])).append("-").append(
								byte2String(data[7])).append("-").append(
								byte2String(data[6])).append(" ").append(
								byte2String(data[5])).append(":").append(
								byte2String(data[4])).toString()
								+ ":00";

						// 将零序电流值以:拼接串
						StringBuffer zeroSequenceCurrentBuffer = new StringBuffer();
						String lastVal = "";
						for (int i = 0 + 11; i < data.length; i += 3) {

							if (!"ee"
									.equalsIgnoreCase(byte2String(data[i + 2]))) {
								String highBin = ConvertInXBaseUtil
										.decimal2Binary(ConvertInXBaseUtil
												.byte2Decimal(data[i + 2]),
												true);
								String s = highBin.substring(0, 1);
								String high = ConvertInXBaseUtil.binary2Hex("0"
										+ highBin.substring(1));
								// String high = byte2String(data[i + 2]);
								String middle = byte2String(data[i + 1]);
								String low = byte2String(data[i]);

								// 如果第一位是1，则表示负数；0表示是正数
								String symbol = "";
								if ("1".equals(s)) {
									symbol = "-";
								}
								String valOfZeroSequenceCurrent = symbol + high
										+ middle.substring(0, 1) + "."
										+ middle.substring(1) + low;
								lastVal = valOfZeroSequenceCurrent;
								zeroSequenceCurrentBuffer
										.append(valOfZeroSequenceCurrent);
							} else {
								zeroSequenceCurrentBuffer.append(lastVal);
							}

							if (data.length - 3 > i) {
								zeroSequenceCurrentBuffer.append(":");
							}
						}

						eventData.put("pnfn", "0101" + byte2String(data[2])
								+ "0b");
						eventData.put("startTime", startTime);
						eventData.put("zeroSequenceCurrentData",
								zeroSequenceCurrentBuffer.toString());
						Event event = Event.createDataEvent(
								"/source/zeroSequenceCurrent", eventData);
						Dispatcher d = Dispatcher.getInstance();
						d.multicast(event);
					} else if (data[0] == 0x01 && data[1] == 0x01
							&& data[3] == 0x0c
							&& (data[2] == 0x01 || data[2] == 0x04)) {// 正向有功、反向有功电能量曲线

						eventData = new HashMap();
						// 获取起始时间
						StringBuffer sb = new StringBuffer();
						String startTime = sb.append("20").append(
								byte2String(data[8])).append("-").append(
								byte2String(data[7])).append("-").append(
								byte2String(data[6])).append(" ").append(
								byte2String(data[5])).append(":").append(
								byte2String(data[4])).toString()
								+ ":00";

						// 将电能量值以:拼接串
						StringBuffer activePowerEnergyDataBuffer = new StringBuffer();
						String lastVal = "";
						for (int i = 0 + 11; i < data.length; i += 4) {
							if (!"ee"
									.equalsIgnoreCase(byte2String(data[i + 3]))) {
								String high = byte2String(data[i + 3]);
								String middle1 = byte2String(data[i + 2]);
								String middle2 = byte2String(data[i + 1]);
								String low = byte2String(data[i]);

								String valOfActivePowerEnergy = high + middle1
										+ "." + middle2 + low;
								lastVal = valOfActivePowerEnergy;
								activePowerEnergyDataBuffer
										.append(valOfActivePowerEnergy);
							} else {
								activePowerEnergyDataBuffer.append(lastVal);
							}

							if (data.length - 4 > i) {
								activePowerEnergyDataBuffer.append(":");
							}
						}

						eventData.put("pnfn", "0101" + byte2String(data[2])
								+ "0c");
						eventData.put("startTime", startTime);
						eventData.put("activePowerEnergyData",
								activePowerEnergyDataBuffer.toString());
						Event event = Event.createDataEvent(
								"/source/activePowerEnergy", eventData);
						Dispatcher d = Dispatcher.getInstance();
						d.multicast(event);

					} else if (data[0] == 0x01 && data[1] == 0x01
							&& data[3] == 0x0c
							&& (data[2] == 0x02 || data[2] == 0x08)) {// 正向无功、反向无功电能量曲线

						eventData = new HashMap();
						// 获取起始时间
						StringBuffer sb = new StringBuffer();
						String startTime = sb.append("20").append(
								byte2String(data[8])).append("-").append(
								byte2String(data[7])).append("-").append(
								byte2String(data[6])).append(" ").append(
								byte2String(data[5])).append(":").append(
								byte2String(data[4])).toString()
								+ ":00";

						// 将电能量值以:拼接串
						StringBuffer reactivePowerEnergyDataBuffer = new StringBuffer();
						String lastVal = "";
						for (int i = 0 + 11; i < data.length; i += 4) {
							if (!"ee"
									.equalsIgnoreCase(byte2String(data[i + 3]))) {
								String high = byte2String(data[i + 3]);
								String middle1 = byte2String(data[i + 2]);
								String middle2 = byte2String(data[i + 1]);
								String low = byte2String(data[i]);

								String valOfReactivePowerEnergy = high
										+ middle1 + "." + middle2 + low;
								lastVal = valOfReactivePowerEnergy;
								reactivePowerEnergyDataBuffer
										.append(valOfReactivePowerEnergy);
							} else {
								reactivePowerEnergyDataBuffer.append(lastVal);
							}

							if (data.length - 4 > i) {
								reactivePowerEnergyDataBuffer.append(":");
							}
						}

						eventData.put("pnfn", "0101" + byte2String(data[2])
								+ "0c");
						eventData.put("startTime", startTime);
						eventData.put("reactivePowerEnergyData",
								reactivePowerEnergyDataBuffer.toString());
						Event event = Event.createDataEvent(
								"/source/reactivePowerEnergy", eventData);
						Dispatcher d = Dispatcher.getInstance();
						d.multicast(event);

					} else if (data[0] == 0x01 && data[1] == 0x01
							&& data[3] == 0x0c
							&& (data[2] == 0x10 || data[2] == 0x40)) {// 正向有功、反向功电能示数曲线

						eventData = new HashMap();
						// 获取起始时间
						StringBuffer sb = new StringBuffer();
						String startTime = sb.append("20").append(
								byte2String(data[8])).append("-").append(
								byte2String(data[7])).append("-").append(
								byte2String(data[6])).append(" ").append(
								byte2String(data[5])).append(":").append(
								byte2String(data[4])).toString()
								+ ":00";

						// 将电能量值以:拼接串
						StringBuffer activePowerIndicationDataBuffer = new StringBuffer();
						String lastVal = "";
						for (int i = 0 + 11; i < data.length; i += 4) {
							if (!"ee"
									.equalsIgnoreCase(byte2String(data[i + 3]))) {
								String high = byte2String(data[i + 3]);
								String middle1 = byte2String(data[i + 2]);
								String middle2 = byte2String(data[i + 1]);
								String low = byte2String(data[i]);

								String valOfActivePowerIndication = high
										+ middle1 + middle2 + "." + low;
								lastVal = valOfActivePowerIndication;
								activePowerIndicationDataBuffer
										.append(valOfActivePowerIndication);
							} else {
								activePowerIndicationDataBuffer.append(lastVal);
							}

							if (data.length - 4 > i) {
								activePowerIndicationDataBuffer.append(":");
							}
						}

						eventData.put("pnfn", "0101" + byte2String(data[2])
								+ "0c");
						eventData.put("startTime", startTime);
						eventData.put("activePowerIndicationData",
								activePowerIndicationDataBuffer.toString());
						Event event = Event.createDataEvent(
								"/source/activePowerIndication", eventData);
						Dispatcher d = Dispatcher.getInstance();
						d.multicast(event);

					} else if (data[0] == 0x01
							&& data[1] == 0x01
							&& data[3] == 0x0c
							&& (data[2] == 0x20 || ConvertInXBaseUtil
									.byte2Decimal(data[2]) == 0x80)) {// 正向无功、反向无功电能示数曲线

						eventData = new HashMap();
						// 获取起始时间
						StringBuffer sb = new StringBuffer();
						String startTime = sb.append("20").append(
								byte2String(data[8])).append("-").append(
								byte2String(data[7])).append("-").append(
								byte2String(data[6])).append(" ").append(
								byte2String(data[5])).append(":").append(
								byte2String(data[4])).toString()
								+ ":00";

						// 将电能量值以:拼接串
						StringBuffer reactivePowerIndicationDataBuffer = new StringBuffer();
						String lastVal = "";
						for (int i = 0 + 11; i < data.length; i += 4) {
							if (!"ee"
									.equalsIgnoreCase(byte2String(data[i + 3]))) {
								String high = byte2String(data[i + 3]);
								String middle1 = byte2String(data[i + 2]);
								String middle2 = byte2String(data[i + 1]);
								String low = byte2String(data[i]);

								String valOfActivePowerIndication = high
										+ middle1 + middle2 + "." + low;
								lastVal = valOfActivePowerIndication;
								reactivePowerIndicationDataBuffer
										.append(valOfActivePowerIndication);
							} else {
								reactivePowerIndicationDataBuffer
										.append(lastVal);
							}

							if (data.length - 4 > i) {
								reactivePowerIndicationDataBuffer.append(":");
							}
						}

						eventData.put("pnfn", "0101" + byte2String(data[2])
								+ "0c");
						eventData.put("startTime", startTime);
						eventData.put("reactivePowerIndicationData",
								reactivePowerIndicationDataBuffer.toString());
						Event event = Event.createDataEvent(
								"/source/reactivePowerIndication", eventData);
						Dispatcher d = Dispatcher.getInstance();
						d.multicast(event);
					}

				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** Error occurred. */
	public void onError(String message) {
		p(message);
	}

	/** Abort event from server. */
	public void onAbort(Event theEvent) {
		p("onAbort received: " + theEvent);
	}

	/** Data event from server. */
	public void onData(Event theEvent) {
		// Calculate round trip delay

	}

	/** Heartbeat event from server. */
	public void onHeartbeat(Event theEvent) {
		p("onHeartbeat received: " + theEvent);
	}

	/** Generic print. */
	public void p(String s) {
		// System.out.println("[PushletPing] " + s);
	}

	/*
	 * 终端地址整型转为16进制 不足8位前段加0 eg: str=10731 那么返回的是:07310001
	 */
	public String add_0_pre(String str) {
		String b_ertuAddr2 = str;
		if (str.length() < 8) {
			int i = str.length();
			for (; i < 8; i++) {
				b_ertuAddr2 = "0" + b_ertuAddr2;
			}
		}
		return b_ertuAddr2.substring(4) + b_ertuAddr2.substring(0, 4);
	}

	// byte array 转换成 16进制 字符串
	public static String getHexString(byte[] b) throws Exception {
		String result = "";
		for (int i = 0; i < b.length; i++) {
			result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1)
					+ " ";
		}
		return result;
	}

	// 获取配置项目信息
	public String getPropertiesByParams(String file, String paramname) {
		try {
			TestProperties ec = TestProperties.getInstance();
			String str = ec.getPropertyValue(file, paramname);
			return str;
		} catch (Exception e) {
			e.printStackTrace();
			return "null";
		}
	}

	// 获取是否监测接地故障的配置参数
	public String getEarth_fault_monitor_Parame() {
		return getPropertiesByParams("/heart.properties", "Earth_fault_monitor");
	}

	// 判断否监测接地故障的配置参数返回boolean值
	public boolean getComparison() {
		if (getEarth_fault_monitor_Parame() != null
				&& "true".equals(getEarth_fault_monitor_Parame())) {
			return true;
		} else {
			return false;
		}
	}
}